package demo.fileupdown;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Controller
public class FileController {
    Logger logger = LoggerFactory.getLogger(FileController.class);

    // 定义一个实例变量，用于保存文件内容
    //  在实际环境中，要把上传的文件写入数据库，或文件中
    UploadFileInfo file;

    @GetMapping("/file-upload")
    public String upload() {
        return "file/upload";
    }

    @PostMapping("/file-upload")
    public String upload(Model model, MultipartFile photofile) {
        try {
            if (photofile != null && photofile.getSize() > 0) {
                file = new UploadFileInfo();
                file.name = photofile.getOriginalFilename();
                file.mime = photofile.getContentType();
                file.size = photofile.getSize();
                file.data = photofile.getBytes();
                logger.info("上传文件成功：" + file.toString());
            }
        } catch (IOException e) {
            logger.error("上传文件失败", e);
            throw new RuntimeException("file upload failed", e);
        }
        model.addAttribute("filename", file.name);
        return "file/show";
    }

    // 下载文件，在html中使用<img>标签显示图像，与下载文件的处理方法是一样的。
    @GetMapping("/file-download")
    public ResponseEntity<byte[]> download() {
        if (file == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf(file.mime));
        return new ResponseEntity<>(file.data, headers, HttpStatus.OK);
    }
}
